package com.example.yyh.recorddemo.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import com.example.yyh.recorddemo.R;
import com.example.yyh.recorddemo.base.BaseActivity;
import com.example.yyh.recorddemo.bean.SoundBean;
import com.example.yyh.recorddemo.databinding.ActivityMainBinding;
import com.example.yyh.recorddemo.manager.RecordDbManager;
import com.example.yyh.recorddemo.manager.RecordManager;
import com.example.yyh.recorddemo.permission.PermissionCons;
import com.example.yyh.recorddemo.utils.DateUtils;
import com.example.yyh.recorddemo.utils.FileUtils;

import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 录制页面
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> {

    private int RECORD_LENGTH;//录制的时长

    private WeakHandler mHandler;//处理过泄漏Handler

    private RecordManager mRecordManager;//录制工具类

    private Animation mAnimation;//简单的旋转动画，加上录制不再单调

    private SharedPreferences mSharePF;//判断是否是第一次安装

    private String ISFIRSTLOGIN = "first_login";//


    /**
     * 处理Handler内存泄漏
     */
    private static class WeakHandler extends Handler {
        private WeakReference<MainActivity> mActivity;

        public WeakHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mActivity.get();
            TextView tvRecordTime = activity.findViewById(R.id.tv_record_time);
            switch (msg.what) {
                case 1:
                    activity.RECORD_LENGTH += 1000;
                    tvRecordTime.setText(DateUtils.getMSTime(activity.RECORD_LENGTH));
                    sendEmptyMessageDelayed(1, 1000);
                    break;
            }
        }
    }

    /**
     * 处理权限回调
     *
     * @param requestCode
     */
    @Override
    protected void checkPermissionSuccess(int requestCode) {
        super.checkPermissionSuccess(requestCode);
        if (PermissionCons.RECORD_AUDIO == requestCode) {
            if (!mRecordManager.isRecord()) {
                mAnimation = AnimationUtils.loadAnimation(this, R.anim.rorate);
                mAnimation.setRepeatMode(Animation.RESTART);
                mContentBindingView.anim.startAnimation(mAnimation);
                mContentBindingView.setIsStart(false);
                mRecordManager.startRecord();
                //现在开始 符号显示停止
                //mContentBindingView.ivRecord.setImageResource(R.mipmap.icon_stop);
                mContentBindingView.ivRecord.setImageResource(R.mipmap.miku_xian);
                mContentBindingView.tvRecord.setText(getString(R.string.stop));
                mHandler.sendEmptyMessage(1);
            } else {
                mAnimation.cancel();
                File file = mRecordManager.stopRecord();
                saveSoundInfo(file);
                //mContentBindingView.ivRecord.setImageResource(R.mipmap.icon_microphone);
                mContentBindingView.ivRecord.setImageResource(R.mipmap.miku_fang);
                mHandler.removeCallbacksAndMessages(null);
                RECORD_LENGTH = 0;
                mContentBindingView.tvRecordTime.setText(DateUtils.getMSTime(RECORD_LENGTH));
                mContentBindingView.tvRecord.setText(getString(R.string.record));
                if (!mSharePF.getBoolean(ISFIRSTLOGIN, false)) {//判断是否是第一次登录，如果是录制完跳转录音列表
                    mSharePF.edit().putBoolean(ISFIRSTLOGIN, true).commit();
                    RecordListActivity.show(this);
                }
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSharePF = getSharedPreferences("recorder", Context.MODE_PRIVATE);
    }

    @Override
    protected void initData() {
        mRecordManager = RecordManager.getInstance();
        mRecordManager.setContext(this);
        //初始默认隐藏删除和停止按钮
        mContentBindingView.setIsStart(false);
        //检查是否开启录音权限
//        checkPermission(PermissionCons.RECORD_AUDIO, recordPermission);
        mHandler = new WeakHandler(this);
    }

    @Override
    protected void setListener() {
        //mvvm又调皮了
        mContentBindingView.setOnClick(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.record://录制或者暂停录制
                checkPermission(PermissionCons.RECORD_AUDIO, recordPermission);//检查是否开启内存访问权限
                break;
            case R.id.menu://录制的音频列表
                RecordListActivity.show(this);
                break;
        }
    }


    /**
     * 把录制信息存入本地数据库
     *
     * @param file
     */
    private void saveSoundInfo(final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(file.lastModified()));
                String fileSize = FileUtils.getFileSize(file.length());
                String filePath = file.getAbsolutePath();
                String fileName = FileUtils.getFileNameNoEx(file.getName());
                SoundBean soundBean = new SoundBean();
                soundBean.setId(String.valueOf(System.currentTimeMillis()));
                soundBean.setFilePath(filePath);
                soundBean.setName(fileName);
                soundBean.setFileSize(fileSize);
                soundBean.setTime(time);
                Log.e("debug", "id--->" + System.currentTimeMillis());
                Log.e("debug", "文件创建时间-->" + time);
                Log.e("debug", "文件大小-->" + fileSize);
                Log.e("debug", "文件路径-->" + filePath);
                Log.e("debug", "文件名称-->" + fileName);
                RecordDbManager.getInstance().saveOrUpdate(soundBean);
            }
        }).start();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRecordManager.isRecord()) {
            mRecordManager.releaseRecord();
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);//Handler移除消息
        }

        if (mAnimation != null) {
            mAnimation.cancel();
            mAnimation = null;
        }
    }

}
